//
//  ImageWorkedViewController.m
//  Scanner
//
//  Created by TGBUS on 12-7-14.
//  Copyright (c) 2012年 __MyCompanyName__. All rights reserved.
//

#import "ImageWorkedViewController.h"
#import "ImageUtlity.h"
#import "UIImage+Extension.h"
#import "ImageProcessViewController.h"

@interface ImageWorkedViewController () {
@private
}

-(void)showFrontView:(BOOL)flag;
-(void)processThunmnailImg:(CGSize)thunmSize;     //生成缩略图,存到本地
-(void)undoAction:(id)sender;                       //Undo操作
-(void)clearAction:(id)sender;                      //Clear操作
-(void)rgbViewAction:(id)sender;                    //显示调节RGB的滑竿操作
-(void)enableControllers:(NSNumber *)flag;          //是否禁用控件
-(void)useAction:(id)sender;                        //结束处理图片操作
-(void)sliderChanged:(id)sender;                    //滑竿滑动停止后的处理事件
@end

@implementation ImageWorkedViewController

@synthesize brightImgView,blanceImgView;
@synthesize context,metrixFilter,colorFilter,processImage,colorFilter2;
@synthesize imageProcessDelegate;
@synthesize sourceImagePath;
@synthesize sliderView;
@synthesize imgView;
@synthesize bottomToolBar;
@synthesize segmentController;
@synthesize redSlider,greenSlider,blueSlider,brightSlider,contrastSlider;
@synthesize lblRedToCyan,lblBright,lblContrast;
@synthesize brightLeftImgView,brightRightImgView,contrastLeftImgView,contrastRightImgView,redLeftImgView,redRightImgView,greenLeftImgView,greenRightImgView,blueLeftImgView,blueRightImgView;


-(id)initWithPhotoType:(int)_photoType
{
    self=[super init];
    if(self)
    {
        photoType=_photoType;
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma -mark Private Method

-(void)processThunmnailImg:(CGSize)thunmSize
{
    
       //制作缩略图
    UIImage *thumbnailImg=[UIImage imageWithContentsOfFile:kPhotoedImagePath];
    
//    if(thumbnailImg!=nil)
//    {
//        UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"" message:[NSString stringWithFormat:@"读取刚才拍摄的照片成功!%@",kPhotoedImagePath] delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
//        [alert show];
//        [alert release];
//    }
//    else
//    {
//        UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"" message:[NSString stringWithFormat:@"读取刚才拍摄的照片失败!%@",kPhotoedImagePath] delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
//        [alert show];
//        [alert release];
//    }

    UIGraphicsBeginImageContext(thunmSize);
    [thumbnailImg drawInRect:CGRectMake(0, 0, thunmSize.width, thunmSize.height)];
    thumbnailImg = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    NSData *data=UIImagePNGRepresentation(thumbnailImg);
    [data writeToFile:kPhotoProcessingImagePath atomically:YES];
    
//    NSFileManager *fileManger=[NSFileManager defaultManager];
//    if([fileManger fileExistsAtPath:kPhotoProcessingImagePath])
//    {
//        UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"" message:[NSString stringWithFormat:@"生成缩略图照片成功!%@",kPhotoProcessingImagePath] delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
//        [alert show];
//        [alert release];
//    }
//    else
//    {
//        UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"" message:[NSString stringWithFormat:@"生成缩略图照片失败!%@",kPhotoProcessingImagePath] delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
//        [alert show];
//        [alert release];
//    }
}

-(void)showFrontView:(BOOL)flag
{
    [redSlider setHidden:flag];
    [greenSlider setHidden:flag];
    [blueSlider setHidden:flag];
    [lblRedToCyan setHidden:flag];
    [redLeftImgView setHidden:flag];
    [redRightImgView setHidden:flag];
    [greenLeftImgView setHidden:flag];
    [greenRightImgView setHidden:flag];
    [blueLeftImgView setHidden:flag];
    [blueRightImgView setHidden:flag];
    [blanceImgView setHidden:flag];
   
    
    [lblBright setHidden:!flag];
    [lblContrast setHidden:!flag];
    [brightSlider setHidden:!flag];
    [contrastSlider setHidden:!flag];
    [brightLeftImgView setHidden:!flag];
    [brightRightImgView setHidden:!flag];
    [contrastLeftImgView setHidden:!flag];
    [contrastRightImgView setHidden:!flag];
    [brightImgView setHidden:!flag];
}

-(void)refreshImageView
{
    [imgView setImage:[UIImage imageWithContentsOfFile:kPhotoProcessingImagePath]];
    self.processImage=[CIImage imageWithContentsOfURL:[NSURL fileURLWithPath:kPhotoProcessingImagePath]];
}

-(void)undoAction:(id)sender
{
    CATransition *transition=[CATransition animation];
    transition.duration=1.0;
    transition.timingFunction=[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
    transition.type=@"oglFlip";
    transition.subtype=kCATransitionFromBottom;
    [imgView.layer addAnimation:transition forKey:nil];
    if(isClear)
    {
        [self clearAction:nil];
    }
    else
    {
        float redValue=0;
        float greenValue=0;
        float blueValue=0;
        float brightValue=0;
        float contrastVlaue=1;
        switch (photoType) {
            case PhotoSlidersType:
                redValue=-0.1;
                greenValue=0.3;
                blueValue=0.55;
                break;
            case PhotoNegativeType:
            {   
                redValue=-0.4;
                greenValue=0.15;
                blueValue=0.26;
            }
                break;
            case Photo35Type:
                redValue=0.08;
                greenValue=0.16;
                blueValue=0.54;
                break;
            case Photo46Type:
                redValue=0.05;
                greenValue=0.15;
                blueValue=0.5;
                break;
            default:
                break;
        }
        [redSlider setValue:redValue animated:YES];
        [greenSlider setValue:greenValue animated:YES];
        [blueSlider setValue:blueValue animated:YES];
        [brightSlider setValue:brightValue animated:YES];
        [contrastSlider setValue:contrastVlaue animated:YES];
        [self sliderChanged:nil];
    }
}

-(void)clearAction:(id)sender
{
    isClear=YES;
    //动画形式将滑竿都恢复至中值
    [redSlider setValue:0 animated:YES];
    [greenSlider setValue:0 animated:YES];
    [blueSlider setValue:0 animated:YES];
    [brightSlider setValue:0 animated:YES];
    [contrastSlider setValue:1 animated:YES];
    
    [self refreshImageView];
}

-(void)enableControllers:(NSNumber *)flag
{
    for(int i=0;i<[bottomToolBar.items count];i++)
    {
        if(i!=1)
        {
            UIControl *controller=[bottomToolBar.items objectAtIndex:i];
            [controller setEnabled:[flag boolValue]];
        }
    }
}

-(void)rgbViewAction:(id)sender
{   
    UIButton *btn=(UIButton *)sender;
    if(btn.tag==800&&isBackView==NO)
    {
        [self enableControllers:[NSNumber numberWithBool:NO]];
        CATransition *transition=[CATransition animation];
        transition.duration=1.0;
        transition.timingFunction=[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
        transition.type=@"oglFlip";

        isBackView=YES;
        transition.subtype=kCATransitionFromRight;
        [self showFrontView:isBackView];
        
        [sliderView.layer addAnimation:transition forKey:nil];
        
        [self performSelector:@selector(enableControllers:) withObject:[NSNumber numberWithBool:YES] afterDelay:1.0];  
    }
    else if(btn.tag==801&&isBackView==YES)
    {
        [self enableControllers:[NSNumber numberWithBool:NO]];
        CATransition *transition=[CATransition animation];
        transition.duration=1.0;
        transition.timingFunction=[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
        transition.type=@"oglFlip";

        isBackView=NO;
        transition.subtype=kCATransitionFromLeft;
        [self showFrontView:isBackView];
        
        [sliderView.layer addAnimation:transition forKey:nil];
        
        [self performSelector:@selector(enableControllers:) withObject:[NSNumber numberWithBool:YES] afterDelay:1.0];
    }
}

-(void)useAction:(id)sender
{
    CIImage *originImg=[CIImage imageWithContentsOfURL:[NSURL fileURLWithPath:kPhotoedImagePath]];
    if(originImg==nil)
    {
        UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"" message:[NSString stringWithFormat:@"得到原始图失败%@",kPhotoedImagePath] delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil];
        [alert show];
        [alert release];
    }
    
    //处理原图
    //RGB像素处理
    [metrixFilter setValue:originImg forKey:kCIInputImageKey];
    [metrixFilter setValue:[CIVector vectorWithX:(redSlider.maximumValue-redSlider.value) Y:0 Z:0] forKey:@"inputRVector"];
    [metrixFilter setValue:[CIVector vectorWithX:0 Y:(greenSlider.maximumValue-greenSlider.value) Z:0] forKey:@"inputGVector"];
    [metrixFilter setValue:[CIVector vectorWithX:0 Y:0 Z:(blueSlider.maximumValue-blueSlider.value)] forKey:@"inputBVector"];
    
    CIImage *outMetrixImage=[metrixFilter outputImage];
    
    //颜色--亮度和对比度处理
    [colorFilter setValue:outMetrixImage forKey:kCIInputImageKey];
    [colorFilter setValue:[NSNumber numberWithFloat:contrastSlider.value] forKey:@"inputContrast"];
    [colorFilter setValue:[NSNumber numberWithFloat:0-brightSlider.value] forKey:@"inputBrightness"];
    CIImage *outImage=[colorFilter outputImage];
    
    CGImageRef cgImg=[context createCGImage:outImage fromRect:outImage.extent];
    

    UIImage *newImg=[UIImage imageWithCGImage:cgImg];

    if(newImg==nil)
    {
        UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"" message:[NSString stringWithFormat:@"获取处理后的图片失败!"] delegate:nil cancelButtonTitle:@"OK" otherButtonTitles: nil];
        [alert show];
        [alert release];
    }
    if([imageProcessDelegate respondsToSelector:@selector(ImageProcessedFinished:)])
    {
        [imageProcessDelegate ImageProcessedFinished:newImg];
    }
    [self dismissModalViewControllerAnimated:YES];
}

-(void)sliderChanged:(id)sender
{
    if(processImage==nil)
    {
        NSLog(@"要处理的图片是nil");
        return;
    }
    //RGB像素处理
    [metrixFilter setValue:processImage forKey:kCIInputImageKey];
    [metrixFilter setValue:[CIVector vectorWithX:(redSlider.maximumValue-redSlider.value) Y:0 Z:0] forKey:@"inputRVector"];
    [metrixFilter setValue:[CIVector vectorWithX:0 Y:(greenSlider.maximumValue-greenSlider.value) Z:0] forKey:@"inputGVector"];
    [metrixFilter setValue:[CIVector vectorWithX:0 Y:0 Z:(blueSlider.maximumValue-blueSlider.value)] forKey:@"inputBVector"];
    
    CIImage *outMetrixImage=[metrixFilter outputImage];
    
    //颜色--亮度和对比度处理
    [colorFilter setValue:outMetrixImage forKey:kCIInputImageKey];
    [colorFilter setValue:[NSNumber numberWithFloat:contrastSlider.value] forKey:@"inputContrast"];
    [colorFilter setValue:[NSNumber numberWithFloat:0-brightSlider.value] forKey:@"inputBrightness"];
    CIImage *outImage=[colorFilter outputImage];
    
    CGImageRef cgImg=[context createCGImage:outImage fromRect:outImage.extent];
    UIImage *newImg=[UIImage imageWithCGImage:cgImg];
    [imgView setImage:newImg];
    CGImageRelease(cgImg);
}

//用于打印所有过滤器的键值
//- (void)logAllFilters {
//    NSArray *properties = [CIFilter filterNamesInCategory:
//                           kCICategoryBuiltIn];
//    NSLog(@"FilterName:\n%@", properties);
//    for (NSString *filterName in properties) {
//        CIFilter *fltr = [CIFilter filterWithName:filterName];
//        NSLog(@"%@:\n%@", filterName, [fltr attributes]);
//    }
//}

#pragma mark - View lifecycle

// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView
{
    [super loadView];

    [self.view setBackgroundColor:[UIColor blackColor]];
    
    //显示的照片
    imgView=[[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 320, 440)];
    [self.view addSubview:imgView];
        
    
    //----------------------------标签和滑竿-------------------------
    CGFloat orginX=33;
    CGFloat height=29;
    CGFloat sliderWidth=205;

    //承载滑竿的视图
    sliderView=[[UIView alloc] initWithFrame:CGRectMake(29.5, 139, 271, 150)];
    [sliderView setBackgroundColor:[[UIColor grayColor] colorWithAlphaComponent:0.6]];
    sliderView.layer.cornerRadius=8;
    [sliderView setHidden:YES];
    [self.view addSubview:sliderView];
    
    
    
    lblRedToCyan=[[UILabel alloc] initWithFrame:CGRectMake(orginX-20, 5, sliderWidth, height)];
    [lblRedToCyan setTextColor:[UIColor blackColor]];
    [lblRedToCyan setFont:[UIFont boldSystemFontOfSize:18]];
    [lblRedToCyan setTextAlignment:UITextAlignmentLeft];
    [lblRedToCyan setBackgroundColor:[UIColor clearColor]];
    [lblRedToCyan setText:@"Balance"];
    [sliderView addSubview:lblRedToCyan];
    
    redSlider=[[UISlider alloc] initWithFrame:CGRectMake(orginX, lblRedToCyan.frame.origin.y+height, sliderWidth, height)];
    [redSlider setTag:500];
    [redSlider setMaximumTrackImage:[UIImage imageNamed:@"slider.png"] forState:UIControlStateNormal];
    [redSlider setMinimumTrackImage:[UIImage imageNamed:@"slider.png"] forState:UIControlStateNormal];
    [redSlider setThumbImage:[UIImage imageNamed:@"slider_bar.png"] forState:UIControlStateNormal];
    [redSlider addTarget:self action:@selector(sliderChanged:) forControlEvents:UIControlEventTouchUpInside];
    [redSlider setMaximumValue:1];
    [redSlider setMinimumValue:-1];
    [sliderView addSubview:redSlider];
    
    greenSlider=[[UISlider alloc] initWithFrame:CGRectMake(orginX,  redSlider.frame.origin.y+height+7, sliderWidth, height)];
    [greenSlider setTag:501];
    [greenSlider setMaximumTrackImage:[UIImage imageNamed:@"slider.png"] forState:UIControlStateNormal];
    [greenSlider setMinimumTrackImage:[UIImage imageNamed:@"slider.png"] forState:UIControlStateNormal];
    [greenSlider setThumbImage:[UIImage imageNamed:@"slider_bar.png"] forState:UIControlStateNormal];
    [greenSlider addTarget:self action:@selector(sliderChanged:) forControlEvents:UIControlEventTouchUpInside];
    [greenSlider setMaximumValue:1];
    [greenSlider setMinimumValue:-1];
    [sliderView addSubview:greenSlider];
    
    blueSlider=[[UISlider alloc] initWithFrame:CGRectMake(orginX,  greenSlider.frame.origin.y+height+7, sliderWidth, height)];
    [blueSlider setTag:502];
    [blueSlider setMaximumTrackImage:[UIImage imageNamed:@"slider.png"] forState:UIControlStateNormal];
    [blueSlider setMinimumTrackImage:[UIImage imageNamed:@"slider.png"] forState:UIControlStateNormal];
    [blueSlider setThumbImage:[UIImage imageNamed:@"slider_bar.png"] forState:UIControlStateNormal];
    [blueSlider setMaximumValue:1];
    [blueSlider setMinimumValue:-1];
    [blueSlider addTarget:self action:@selector(sliderChanged:) forControlEvents:UIControlEventTouchUpInside];
    [sliderView addSubview:blueSlider];
  
    //调节亮度和对比度的
    CGFloat height2=30;
    lblBright=[[UILabel alloc] initWithFrame:CGRectMake(orginX-20,5, sliderWidth, height2)];
    [lblBright setTextColor:[UIColor blackColor]];
    [lblBright setTextAlignment:UITextAlignmentLeft];
    [lblBright setBackgroundColor:[UIColor clearColor]];
    [lblBright setFont:[UIFont systemFontOfSize:18]];
    [lblBright setFont:[UIFont boldSystemFontOfSize:18]];
    [lblBright setText:@"Brightness"];
    [lblBright setHidden:YES];
    [sliderView addSubview:lblBright];
    
    brightSlider=[[UISlider alloc] initWithFrame:CGRectMake(orginX,  lblBright.frame.origin.y+height2, sliderWidth, height)];
    [brightSlider setTag:503];
    [brightSlider setMaximumTrackImage:[UIImage imageNamed:@"slider.png"] forState:UIControlStateNormal];
    [brightSlider setMinimumTrackImage:[UIImage imageNamed:@"slider.png"] forState:UIControlStateNormal];
    [brightSlider setThumbImage:[UIImage imageNamed:@"slider_bar.png"] forState:UIControlStateNormal];
    [brightSlider setMaximumValue:1];
    [brightSlider setMinimumValue:-1];
    [brightSlider setHidden:YES];
    [brightSlider addTarget:self action:@selector(sliderChanged:) forControlEvents:UIControlEventTouchUpInside];
    [sliderView addSubview:brightSlider];

    lblContrast=[[UILabel alloc] initWithFrame:CGRectMake(orginX-20,brightSlider.frame.origin.y+height2, sliderWidth, height2)];
    [lblContrast setTextColor:[UIColor blackColor]];
    [lblContrast setTextAlignment:UITextAlignmentLeft];
    [lblContrast setBackgroundColor:[UIColor clearColor]];
    [lblContrast setFont:[UIFont systemFontOfSize:18]];
    [lblContrast setFont:[UIFont boldSystemFontOfSize:18]];
    [lblContrast setText:@"Contrast"];
    [lblContrast setHidden:YES];
    [sliderView addSubview:lblContrast];
    
    contrastSlider=[[UISlider alloc] initWithFrame:CGRectMake(orginX,  lblContrast.frame.origin.y+height2, sliderWidth, height)];
    [contrastSlider setTag:504];
    [contrastSlider setMaximumTrackImage:[UIImage imageNamed:@"slider.png"] forState:UIControlStateNormal];
    [contrastSlider setMinimumTrackImage:[UIImage imageNamed:@"slider.png"] forState:UIControlStateNormal];
    [contrastSlider setThumbImage:[UIImage imageNamed:@"slider_bar.png"] forState:UIControlStateNormal];
    [contrastSlider setHidden:YES];
    [contrastSlider setMaximumValue:4];
    [contrastSlider setMinimumValue:0];
    [contrastSlider addTarget:self action:@selector(sliderChanged:) forControlEvents:UIControlEventTouchUpInside];
    [sliderView addSubview:contrastSlider];
    
    
    
    //滑竿旁边的10个小圆点图片
    brightLeftImgView=[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"dot_white.png"]];
    [brightLeftImgView setFrame:CGRectMake(13, brightSlider.frame.origin.y+5, 18, 19)];
    [sliderView addSubview:brightLeftImgView];
    
    brightRightImgView=[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"dot_black.png"]];
    [brightRightImgView setFrame:CGRectMake(brightSlider.frame.origin.x+brightSlider.frame.size.width+5, brightSlider.frame.origin.y+5, 18, 19)];
    [sliderView addSubview:brightRightImgView];
    
    contrastLeftImgView=[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"dot_white.png"]];
    [contrastLeftImgView setFrame:CGRectMake(13, contrastSlider.frame.origin.y+5, 18, 19)];
    [sliderView addSubview:contrastLeftImgView];
    
    contrastRightImgView=[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"dot_black.png"]];
    [contrastRightImgView setFrame:CGRectMake(contrastSlider.frame.origin.x+contrastSlider.frame.size.width+5, contrastSlider.frame.origin.y+5, 18, 19)];
    [sliderView addSubview:contrastRightImgView];
    
    redLeftImgView=[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"dot_red.png"]];
    [redLeftImgView setFrame:CGRectMake(13, redSlider.frame.origin.y+5, 18, 19)];
    [sliderView addSubview:redLeftImgView];
    
    redRightImgView =[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"dot_cyan.png"]];
    [redRightImgView setFrame:CGRectMake(redSlider.frame.origin.x+redSlider.frame.size.width+5, redSlider.frame.origin.y+5, 18, 19)];
    [sliderView addSubview:redRightImgView];
    
    greenLeftImgView=[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"dot_green.png"]];
    [greenLeftImgView setFrame:CGRectMake(13, greenSlider.frame.origin.y+5, 18, 19)];
    [sliderView addSubview:greenLeftImgView];
    
    greenRightImgView=[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"dot_purpleRed.png"]];
    [greenRightImgView setFrame:CGRectMake(greenSlider.frame.origin.x+greenSlider.frame.size.width+5, greenSlider.frame.origin.y+5, 18, 19)];
    [sliderView addSubview:greenRightImgView];

    blueLeftImgView=[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"dot_blue.png"]];
    [blueLeftImgView setFrame:CGRectMake(13, blueSlider.frame.origin.y+5, 18, 19)];
    [sliderView addSubview:blueLeftImgView];
    
    blueRightImgView=[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"dot_yellow.png"]];
    [blueRightImgView setFrame:CGRectMake(blueSlider.frame.origin.x+blueSlider.frame.size.width+5, blueSlider.frame.origin.y+5, 18, 19)];
    [sliderView addSubview:blueRightImgView];

    [self showFrontView:NO];
    
    
    //--------------------底部的操作栏------------------------------------------
    bottomToolBar=[[UIToolbar alloc] initWithFrame:CGRectMake(0, 440, 320, 44)];
    
    //Undo Bar
    UIButton *btnUndo=[UIButton buttonWithType:UIButtonTypeCustom];
    [btnUndo setBackgroundImage:[UIImage imageNamed:@"tool_undo.png"] forState:UIControlStateNormal];
    [btnUndo setFrame:CGRectMake(0, 0, 52, 31)];
    [btnUndo addTarget:self action:@selector(undoAction:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *undoBar=[[[UIBarButtonItem alloc] initWithCustomView:btnUndo] autorelease];
    
    //Clear Bar
    UIButton *btnClear=[UIButton buttonWithType:UIButtonTypeCustom];
    [btnClear setBackgroundImage:[UIImage imageNamed:@"tool_clear.png"] forState:UIControlStateNormal];
    [btnClear setFrame:CGRectMake(0, 0, 52, 31)];
    [btnClear addTarget:self action:@selector(clearAction:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *clearBar=[[[UIBarButtonItem alloc] initWithCustomView:btnClear] autorelease];
    
    //空格1
    UIBarButtonItem *spaceBarOne=[[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFlexibleSpace target:self action:nil] autorelease];
    [spaceBarOne setWidth:10];
    
    
    UIView *segView=[[[UIView alloc] initWithFrame:CGRectMake(0, 0, 89, 33)] autorelease];
    [segView setBackgroundColor:[UIColor colorWithPatternImage:[UIImage imageNamed:@"tool_segment_bg.png"]]];
    
    UIButton *btnBright=[UIButton buttonWithType:UIButtonTypeCustom];
    [btnBright setBackgroundImage:[UIImage imageNamed:@"tool_bright.png"] forState:UIControlStateNormal];
    [btnBright setTag:800];
    [btnBright setFrame:CGRectMake(11, 4.5, 24, 23)];
    [btnBright addTarget:self action:@selector(rgbViewAction:) forControlEvents:UIControlEventTouchUpInside];
    [segView addSubview:btnBright];
    
    UIButton *btnRGB=[UIButton buttonWithType:UIButtonTypeCustom];
    [btnRGB setTag:801];
    [btnRGB setBackgroundImage:[UIImage imageNamed:@"tool_rgb.png"] forState:UIControlStateNormal];
    [btnRGB setFrame:CGRectMake(54, 4.5, 24, 23)];
    [btnRGB addTarget:self action:@selector(rgbViewAction:) forControlEvents:UIControlEventTouchUpInside];
    [segView addSubview:btnRGB];

    //调节rgb和亮度的分段bar
//    segmentController=[[UISegmentedControl alloc] initWithItems:[NSArray arrayWithObjects:@"",@"", nil]];
//    [segmentController setDividerImage:nil forLeftSegmentState:UIControlStateNormal rightSegmentState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
//    [segmentController setSegmentedControlStyle:UISegmentedControlStyleBar];
//    for(UIView *subView in [segmentController subviews])
//    {
//        NSLog(@"%@",subView);
//        [subView setBackgroundColor:[UIColor clearColor]];
//    }
//    [segmentController setBackgroundColor:[UIColor clearColor]];
//    [segmentController setBackgroundImage:[UIImage imageNamed:@"tool_segment_bg.png"] forState:UIControlStateNormal barMetrics:UIBarMetricsDefault];
//    [segmentController setMomentary:YES];
//    [segmentController addTarget:self action:@selector(rgbViewAction:) forControlEvents:UIControlEventValueChanged];
//    [segmentController setFrame:CGRectMake(0, 0, 89, 33)];
//    [segmentController setImage:[UIImage imageNamed:@"tool_bright.png"] forSegmentAtIndex:0];
//    [segmentController setImage:[UIImage imageNamed:@"tool_rgb.png"] forSegmentAtIndex:1];
    
    UIBarButtonItem *segmentBar=[[[UIBarButtonItem alloc] initWithCustomView:segView]autorelease];
    
    //空格2
    UIBarButtonItem *spaceBarTwo=[[[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemFixedSpace target:self action:nil] autorelease];
    [spaceBarTwo setWidth:10];
    
    //Use Bar
    UIButton *btnUse=[UIButton buttonWithType:UIButtonTypeCustom];
    [btnUse setBackgroundImage:[UIImage imageNamed:@"tool_use.png"] forState:UIControlStateNormal];
    [btnUse setFrame:CGRectMake(0, 0, 52, 31)];
    [btnUse addTarget:self action:@selector(useAction:) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem *useBar=[[[UIBarButtonItem alloc]initWithCustomView:btnUse] autorelease];

    [bottomToolBar setItems:[NSArray arrayWithObjects:undoBar,clearBar ,spaceBarOne,segmentBar,spaceBarTwo,useBar,nil]];
    [bottomToolBar setBackgroundImage:[UIImage imageNamed:@"tool_bg.png"] forToolbarPosition:UIToolbarPositionBottom barMetrics:UIBarMetricsDefault];
    [self.view addSubview:bottomToolBar];

    
    
    //左右的下角的小图片
    brightImgView=[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"bright.bmp"]];
    [brightImgView setFrame:CGRectMake(sliderView.frame.origin.x, 400, 32, 32)];
    [brightImgView setHidden:YES];
    [self.view addSubview:brightImgView];
    
    blanceImgView=[[UIImageView alloc] initWithImage:[UIImage imageNamed:@"blance.bmp"]];
    [blanceImgView setFrame:CGRectMake(sliderView.frame.origin.x+sliderView.frame.size.width-32, 400, 32, 32)];
    [blanceImgView setHidden:YES];
    [self.view addSubview:blanceImgView];
    
    
    
    //在本地生成原图的缩略图
    [self processThunmnailImg:imgView.frame.size];
    
    
    
    //进行底片处理
    if(photoType==PhotoNegativeType)
    {
        UIImage *originImg=[UIImage imageWithData:[NSData dataWithContentsOfFile:kPhotoProcessingImagePath]];
        UIImage *newImg=[[ImageUtlity sharedInstance] changedImageFrom:originImg pixel:PixelNegative value:0];
        NSData *data=UIImagePNGRepresentation(newImg);
        [data writeToFile:kPhotoProcessingImagePath atomically:YES];
        [imgView setImage:newImg];
        
        NSFileManager *fileManger=[NSFileManager defaultManager];
//        if([fileManger fileExistsAtPath:kPhotoProcessingImagePath])
//        {
//            UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"" message:[NSString stringWithFormat:@"读取Negative处理照片成功!%@",kPhotoedImagePath] delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
//            [alert show];
//            [alert release];
//        }
//        else
//        {
//            UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"" message:[NSString stringWithFormat:@"读取Negative处理照片失败!%@",kPhotoedImagePath] delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
//            [alert show];
//            [alert release];
//        }
    }
    
    
    //按照预定义rgb滑竿的值进行图片效果调整
    [self undoAction:nil];
    
    
    
    //读取缩略图,创建处理图片的过滤器
    NSURL *url=[NSURL fileURLWithPath:kPhotoProcessingImagePath];
    self.processImage=[CIImage imageWithContentsOfURL:url];
//    self.processImage=[[CIImage alloc] initWithContentsOfURL:[NSURL fileURLWithPath:kPhotoProcessingImagePath]];
    
//    if(processImage!=nil)
//    {
//        UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"" message:[NSString stringWithFormat:@"读取CI格式照片成功!%@",kPhotoedImagePath] delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
//        [alert show];
//        [alert release];
//    }
//    else
//    {
//        UIAlertView *alert=[[UIAlertView alloc] initWithTitle:@"" message:[NSString stringWithFormat:@"读取CI格式照片失败!%@",kPhotoedImagePath] delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
//        [alert show];
//        [alert release];
//        
//    }
         
    // 创建基于GPU的CIContext对象,如果手机处理器达不到，则自动降低为CPU处理,iPhone4和老设备可能有这个问题，4S和touch32G测试无问题
    self.context = [CIContext contextWithOptions: nil];
    
    // 创建基于CPU的CIContext对象
//    self.context = [CIContext contextWithOptions: [NSDictionary dictionaryWithObject:[NSNumber numberWithBool:YES] forKey:kCIContextUseSoftwareRenderer]];
    
    // 创建过滤器
    self.colorFilter = [CIFilter filterWithName:@"CIColorControls"];
    self.colorFilter2 = [CIFilter filterWithName:@"CIColorControls"];
    self.metrixFilter = [CIFilter filterWithName:@"CIColorMatrix"];
    [self sliderChanged:nil];
}

-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    CustomAlert *alert=[[[CustomAlert alloc] initWithMessage:@"Would you like to further adjust EV/color performance"] autorelease];
    [alert setDelegate:self];
    [alert show];
}

-(void)releaseData
{
    self.sliderView=nil;
    self.greenSlider=nil;
    self.blueSlider=nil;
    self.redSlider=nil;
    self.imgView=nil;
    self.lblRedToCyan=nil;
    self.segmentController=nil;
    self.brightSlider=nil;
    self.contrastSlider=nil;
    self.lblBright=nil;
    self.lblContrast=nil;
    self.sourceImagePath=nil;
    self.imageProcessDelegate=nil;
    self.colorFilter=nil;
    self.metrixFilter=nil;
    self.context=nil;
    self.processImage=nil;
    self.brightImgView=nil;
    self.blanceImgView=nil;
    self.brightLeftImgView=nil;
    self.brightRightImgView=nil;
    self.contrastLeftImgView=nil;
    self.contrastRightImgView=nil;
    self.redRightImgView=nil;
    self.redLeftImgView=nil;
    self.greenRightImgView=nil;
    self.greenLeftImgView=nil;
    self.blueLeftImgView=nil;
    self.blueRightImgView=nil;
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    [self releaseData];
}

-(void)dealloc
{
    self.bottomToolBar=nil;
    [self releaseData];
    [super dealloc];
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations
    return (interfaceOrientation == UIInterfaceOrientationPortrait);
}

#pragma mark - CustomAlert Delegate
-(void)customAlertYES:(NSNumber *)index
{
    switch ([index intValue]) {
        case 0://Yes
            [sliderView setHidden:NO];
            [blanceImgView setHidden:NO];
            break;
        case 1://No
            [self useAction:nil];
            break;
        default:
            break;
    }
}

@end
